﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.Mvc;

namespace QuickApp.MVCControl
{
    /// <summary>
    /// 当前登陆用户的相关API
    /// </summary>
    public class UserContext
    {
        #region 单列模式
        private UserContext() { }
        private static UserContext _UserContext = null;
        private static readonly object _lockObj = new object();
        public static UserContext Current
        {
            get
            {
                if (_UserContext == null)
                {
                    lock (_lockObj)
                    {
                        if (_UserContext == null)
                        {
                            _UserContext = new UserContext();
                        }
                    }
                }

                return _UserContext;
            }
        }
        #endregion

        /// <summary>
        /// 当前登录账户的标识
        /// </summary>
        /// <value>The identity.</value>
        public string Identity
        {
            get
            {
                // 如果配置为Debug，则直接返回配置的UserId
                var userId = ConfigurationManager.AppSettings["Debug"];
                if (!string.IsNullOrEmpty(userId))
                {
                    if (!HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        FormsAuthentication.SetAuthCookie(userId, false);
                    }
                    return userId;
                }

                // 如果是认证后用户, 则直接返回登陆的UserId
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    string fuid = HttpContext.Current.User.Identity.Name;
                    return fuid.IndexOf("\\") > 0 ? fuid.Split('\\')[1] : fuid;
                }

                string ssoUid = UserService.GetSSOUserId();
                if (!string.IsNullOrEmpty(ssoUid))
                {
                    FormsAuthentication.SetAuthCookie(ssoUid, false);
                    return ssoUid;
                }
                throw new UnauthorizedAccessException("登录超时!");
            }
        }

        /// <summary>
        /// 判断是否经过认证
        /// </summary>
        public bool IsAuthenticated
        {
            get
            {
                // 如果配置为Debug，则直接返回True
                var userId = ConfigurationManager.AppSettings["Debug"];
                if (!string.IsNullOrEmpty(userId))
                {
                    if (!HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        FormsAuthentication.SetAuthCookie(userId, false);
                    }
                    return true;
                }
                else
                {
                    return HttpContext.Current.User.Identity.IsAuthenticated;
                }
            }
        }

        /// <summary>
        /// 当前登录账户的完整信息
        /// </summary>
        public IUserInfo CurrentUser
        {
            get
            {

                if (HttpContext.Current.Session["UseInfo"] != null)
                {
                    IUserInfo user = HttpContext.Current.Session["UseInfo"] as IUserInfo;
                    return user;
                }
                else
                {
                    IUserInfo u = UserService.GetUserInfo(Identity);
                    HttpContext.Current.Session["UseInfo"] = u;
                    return u;
                }
            }
        }

        /// <summary>
        /// 获取用户的IP
        /// </summary>
        /// <value>The user IP.</value>
        public string UserIP
        {
            get
            {
                return HttpContext.Current.Request.UserHostAddress;
            }
        }

        /// <summary>
        /// 判断当前用户是否在某个角色内
        /// </summary>
        /// <param name="roleCode">角色代码</param>
        /// <returns>
        /// 	<c>true</c> if [is in role] [the specified role code]; otherwise, <c>false</c>.
        /// </returns>
        public bool IsInRole(string roleCode)
        {
            return UserService.IsInRole(Identity, roleCode);
        }

        /// <summary>
        /// 判断是否有权限
        /// </summary>
        /// <param name="rightCode">权限代码</param>
        /// <returns>
        /// 	<c>true</c> if the specified right code has right; otherwise, <c>false</c>.
        /// </returns>
        public bool HasRight(string rightCode)
        {
            return UserService.HasRight(Identity, rightCode);
        }

        /// <summary>
        /// 用户的相关服务
        /// </summary>
        private IUserService UserService
        {
            get
            {
                return DependencyResolver.Current.GetService<IUserService>();
            }
        }
    }
}
